﻿using System.Linq;
using System.Reflection;

namespace Basmus.Values.Attributive
{
    public class DefaultValuesBuilder : IDefaultValuesBuilder
    {
        private readonly IPropertyInfoBuilder _propertyInfoBuilder;

        public DefaultValuesBuilder(IPropertyInfoBuilder propertyInfoBuilder)
        {
            _propertyInfoBuilder = propertyInfoBuilder;
        }

        public DefaultValues Build(ValuesContext valuesContext)
        {
            var propertyInfo = _propertyInfoBuilder.Build(valuesContext);
            var defaultElementsAttribute = propertyInfo
                .GetCustomAttributes(typeof(DefaultElementsAttribute), false)
                .Cast<DefaultElementsAttribute>()
                .Where(x => x.Key == valuesContext.ModelContext.SchemeKey)
                .FirstOrDefault();
            if (defaultElementsAttribute == null)
            {
                return null;
            }
            return new DefaultValues
                       {
                           SetEqualType = defaultElementsAttribute.SetEqualType,
                           Values = defaultElementsAttribute.Values
                       };
        }
    }
}